/**

 * User: seeker910
 * Date: 13-10-24
 * Time: 下午10:26

 */
/*
 define class Rsd.container.Component
 * */
Rsd.define('Rsd.container.Component', {
    extend: 'Rsd.common.ComponentX',
    requires: ['Rsd.common.Layouter'],
    xtype: 'container',
    bodyTagName: 'div',
    /*
    * 布局方式
    * none:不设置
    * vbox:弹性布局， 垂直方向布局
    * hbox:弹性布局， 水平方向
    * fit:弹性布局，容器大小不变，子元素自适应缩放布局
    * border:靠边框布局
    * gird:网格布局
    * auto:块布局，容器大小自动应布局，子元素大小不变
    * {
    *   type: 'fit',
    *   align:'left',//当type为vbox或hbox时，在非主轴方向上（每行或每列）的子元素 对齐方式,即样式：align-items
    *   wrap:'nowrap',//wrap or nowrap
    *   content:'center center'//主轴和交叉的对齐方式
    * }
    * */
    //layout: null,
    /*
    * {
    *    xtype:null,
    *    //承载header的html dom元素
    *    element: null,
    *    //header 的内容对象 ，可以是字符串 也可以是组件
    *    content:null, //{string|control|object}
    *    position: 'top',
    *    //文字对其方式
    *    align: 'center',
    *    space: 10,
    *    cls: null,
    *    style:{},
    *    visible:null
    * }
    * */
    // header: {},
    /*
    * 等于header.content
    * */
    //title: '',
    //鼠标按住头部可拖动
    //draggable:false,
    //是模式对话框
    isDialog: false,
    /*
    *{ 
        tagName:'',
        element:null,
        style:{},
        cls:''
    }
    * */
    //body: null,
    /** 
    * @description 是否显示模态框 和 样式  
    * @example {
    *   背景样式
    *   style:{}
    *   背景是否使用动画
    *   animate:false
    *   value:true
    * }
    * */
    //modular:{value:false,style:null}, 
    /*
    * 按钮延时显示的时间，单位：毫秒
    * */
    delayShow: 50,
    headerTagName: 'div',
    bodyTagName: 'div',
    bodyCls: '',
    //items: [],
    /**
     * @description event:必须初始化前设置，功能等于初始化后的this.on('beforeshow',function(){}),支持IOC
     */
    beforeShow: null,
    /**
     * @description event:必须初始化前设置，功能等于初始化后的this.on('aftershow',function(){}),支持IOC
     */
    afterShow: null,
    /**
     * @description event:必须初始化前设置，功能等于初始化后的this.on('beforeclose',function(){}),支持IOC
     */
    beforeClose: null,
    /**
     * @description event:必须初始化前设置，功能等于初始化后的this.on('afterclose',function(){}),支持IOC
     */
    afterClose: null,
    /**
     * 
     */
    listeners: {},
    /**
     * @description 组件数据源属性是 dataSource ,页面数据源是data 
     */
    //dataSource: null,
    /*
     * @param {object} config
     */
    constructor: function Container(config) {

        config = config || {};
        this.apply(config);
    },
    /**
    * 
    */
    onBeforeInit: function onBeforeInit() {
        var me = this;
        me.callParent();

        if (me.isDialog && me.header.visible && me.closeBtn) {

            var _close = {
                label: {
                    visible: true,
                    content: me.header.content,
                    position: 'left',
                    style: { flex: 1, textAlign: 'unset', fontSize: '130%', overflow: 'hidden' }
                },
                dataSource: {
                    "viewBox": "0 0 1024 1024",
                    "path": "M591.781543 512.091831l417.01993-417.01993a54.522295 54.522295 0 0 0 0-76.777762l-2.304774-2.304774a54.522295 54.522295 0 0 0-76.777762 0l-417.01993 417.740172L95.390981 15.773293a54.522295 54.522295 0 0 0-76.777763 0L16.308445 18.078066a53.585981 53.585981 0 0 0 0 76.777763l417.019929 417.236002-417.019929 417.01993a54.522295 54.522295 0 0 0 0 76.777762l2.304773 2.304773a54.522295 54.522295 0 0 0 76.777763 0l417.019929-417.019929 417.01993 417.019929a54.522295 54.522295 0 0 0 76.777763 0l2.304773-2.304773a54.522295 54.522295 0 0 0 0-76.777762l-417.01993-417.01993z m0 0"
                },
                //margin: '8 8 0 8',
                height: 50,
                width: "100%",
                size: '18 18',
                ctrlCls: 'x-f-close',
                style: me.header.style,
                listeners: {
                    click: {
                        element: 'ctrl',
                        fn: function (sender, event) {
                            me.close();
                        }
                    },
                    mouseover: {
                        element: 'ctrl',
                        fn: function (sender, event) {
                            this.ctrl.element.style.color = 'red';
                            this.ctrl.element.style.cursor = 'pointer';
                        }
                    },
                    mouseout: {
                        element: 'ctrl',
                        fn: function (sender, event) {
                            this.ctrl.element.style.color = 'grey';
                            this.ctrl.element.style.cursor = 'inherit';
                        }
                    }

                }

            };
            me.header.xtype = 'svg';
            me.header.config = _close;
        }
    },
    /*
     * */
    initComponentEx: function initComponentEx() {

        //debugger;
        if (this.header.visible === false) {
            this.body.element = this.dom;
        }
        else {
            //xtype 处理
            if (!Rsd.isEmpty(this.header.xtype)) {
                this.header.content = Rsd.widget(this.header.xtype, this.header.config || this.header);
                this.header.content.parent = this;
                this.header.element = this.header.content.dom;
                //渲染到dom
                this.header.content.renderTo(this.dom);
            }

            if (!this.header.element && this.header.tagName) {
                this.header.element = document.createElement(this.header.tagName);
                this.header.element.style.fontSize = '120%';

                //content 处理
                if (Rsd.isEmpty(this.header.content) && this.header.text) {
                    this.header.content = this.header.text;
                }

                if (Rsd.isString(this.header.content)) {
                    this.header.element.innerHTML = this.header.content;
                }
            }
        }
        //console.log(this.id,this.header.cls );
        //设置header 样式
        if (this.header.element) {
            this.header.element.id = this.id + '_header';
            this.elements['header'] = this.header.element;

            this.header.element.style.display = (this.header.visible == false ? 'none' : '');
            if (Rsd.isEmpty(this.header.xtype)) {
                this.header.element.classList.add('x-header');
            } 
            if (this.header.cls) //Rsd.isEmpty(this.header.xtype) && 
            {
                this.header.element.classList.add(this.header.cls);
            }
        }

        if (!this.body.element && this.body.tagName) {
            this.body.element = document.createElement(this.body.tagName);

        }

        if (this.body.element) {
            this.body.element.id = this.id + '_body';
            this.elements['body'] = this.body.element;

            this.addCls('body', 'x-body');
            this.addCls('body', this.body.cls);

            this.body.element.style.textAlign = this.layout.align;

            if (this.header.visible !== false) {
                var _position = this.header.position || 'top';

                //设置 body  宽度和高度
                switch (_position.toLowerCase()) {
                    case 'top':
                        {
                            //设置宽度
                            this.body.element.style.width = "100%";

                            //设置高度
                        }
                        break;
                    case 'bottom':
                        {
                            //设置宽度
                            this.body.element.style.width = "100%";

                            //设置高度
                        }
                        break;
                    case 'left':
                        {
                            //设置宽度

                            //设置高度
                            this.body.element.style.height = "100%";
                        }
                        break;
                    case 'right':
                        {
                            //设置宽度

                            //设置高度
                            this.body.element.style.height = "100%";
                        }
                        break;
                    default:
                        throw new Error('Property position of header or label is unknown value [' + this.headers.position + '].');
                        break;
                }
            }


            if (this.tip != undefined && this.tip != null) {

                this.body.element.title = this.tip;
            }

            if (this.tabIndex != null) {
                this.body.element.tabIndex = this.tabIndex;
            }
            
            if (this.overflow) {
                this.body.element.style.overflow = this.overflow;
            }

        }

        if (this.draggable) {
            var me = this;
            if (this.header.element) {
                this.header.element.onmouseover = function (e) {
                    me.dom.setAttribute('draggable', true);
                }
            }

            if (this.body.element) {
                this.body.element.onmouseover = function (e) {

                    me.dom.setAttribute('draggable', false);
                }
            }

        }

    },

    /*
    * */
    onAfterInit: function onAfterInit() {
        var me = this;
        this.callParent();
        /*
         * */
        var items = me.items;
        if (Rsd.isArray(items) && items.length > 0) {
            var item;
            for (var i = 0; i < items.length; i++) {
                item = items[i];

                if (!Rsd.isCreated(item)) {
                    var _xtype = item.xtype || ((item.items && item.items.length > 0) ? 'container' : 'component-x');//component-x 占位 ，仅一个div
                    if (me.dependencies[_xtype]) {
                        items[i] = Rsd.create(me.dependencies[_xtype], item);
                    } else {
                        items[i] = Rsd.widget(_xtype, item);
                    }

                    items[i].parent = me;
                }

            }
        }

        //注册事件
        if (this.beforeShow) {
            this.on('beforeshow', this.beforeShow);
        }
        if (this.afterShow) {
            this.on('aftershow', this.afterShow);
        }

        if (this.beforeClose) {
            this.on('beforeclose', this.beforeClose);
        }
        if (this.afterClose) {
            this.on('afterclose', this.afterClose);
        }


    },

    /**
     *
     * @description 执行控件布局，需主动调用。
     * */
    doLayout: function doLayout() {
        //布局自己 异步执行
        this.callParent();
        //监控 doLayout 执行次数
        //console.trace('in contianer doLayout',this.id,this.width);
        var me = this;
        //布局子对象
        setTimeout(function () {
            // 布局子控件
            me.layouter.layoutItems(me);

            for (var i = 0; i < me.items.length; i++) {

                if (me.items[i] instanceof Rsd.common.ComponentX) {
                    //子控件 布局自己内容
                    me.items[i].doLayout();
                }
            }

        }, 50);
        this.isLayout = true;
        return this;
    },

    /**
     *@description 自身render自后，render子对象
     * */
    onAfterRender: function onAfterRender() {

        if (this.header.element) {
            if (this.header.content instanceof Rsd.common.ComponentX) {
                //已在初始化 后渲染到dom
            }
            else {
                this.dom.appendChild(this.header.element);
            }

        }

        if (this.body.element && this.dom != this.body.element) {
            this.dom.appendChild(this.body.element);
        }

        this.callParent();

        var me = this;
        var _item;
        for (var i = 0; i < me.items.length; i++) {
            _item = me.items[i];
            if (!_item instanceof Rsd.common.ComponentX) {
                console.error(me);
                console.error(_item);
                throw new Error('items[' + i + '] is not instanceof Rsd.common.ComponentX in object [' + me.id + '].(Maybe using error xtype.)');
            }
            if (_item.isRendered()) {
                continue;
            }
            _item.renderTo.call(_item, me);


        }
        //可拖动：监听容器内拖动事件
        if (this.isDialog && this.draggable) {
            /*
            *
            * */
            Rsd.onDragOver(null, this.id, function (evt) {
                //console.log('DragOver',evt.dataTransfer.getData('Text'));
            });
            /*
            *
            * */
            Rsd.onDragEnd(this.dom, this.id, function (evt) {
                //拖拽结束
                //console.log(evt)
            });

            /*
            * */
            Rsd.onDrop(null, this.id, function (evt) {

                var _data = Rsd.toJson(evt.dataTransfer.getData('Text'));
                if (_data && _data['cmd'] == 'move') {

                    var _pX = evt.pageX || evt.clientX;
                    var _pY = evt.pageY || evt.clientY;

                    var _x = _data.pageX;
                    var _y = _data.pageY;

                    var tx = _pX - _x + parseInt(me.dom.style.left);
                    var ty = _pY - _y + parseInt(me.dom.style.top);

                    me.dom.style.left = tx + "px";
                    me.dom.style.top = ty + "px";

                    evt.dataTransfer.clearData();
                }
            });

        }
    },
    /**
     * 适时 删除该方法，由addItem代替
     * 追加 
     * @param {*} child 
     */
    add: function add(child) {
        return this.insertItem(-1, child);
    },
    /**
     * 追加
     * @param {*} child 
     */
    addItem: function addItem(child) {
        return this.insertItem(-1, child);
    },
    /**
     * 插入子控件 
     * @param {*} index 位置
     * @param {*} child 子控件
     * @returns 
     */
    insertItem: function insertItem(index, child) {

        var me = this;
        var _c = child;
        if (!_c.render || typeof (_c.render) != 'function') {
            _c = Rsd.widget(_c.xtype, _c);
        }
        _c.parent = me;

        if (index === undefined || index === null || index < 0) {
            me.items.push(_c);
        }
        else {
            me.items.splice(index, 0, _c);
        }

        if (me.isRendered()) {
            _c.renderTo.call(_c, me);
            //me.doLayout();//执行频次过高，添加控件后主动调用doLayout 
            me.isLayout = false;
            setTimeout(function () {
                if (me.isLayout == false) {
                    console.error(me.$className + '添加控件后请调用doLayout方法');
                }
            }, 500);
        }

        return _c;
    },

    /**
     * @description 删除items数组中指定对象
     * */
    removeItem: function removeItem(item) {

        var index = -1;
        for (var i = 0; i < this.items.length; i++) {
            if (this.items[i] == item) {
                index = i;
                break;
            }
        }

        if (index > -1) {
            this.items.splice(index, 1);
        }
    },

    /*
     * 移除所有dom对象
     * */
    removeAll: function removeAll() {

        var me = this;
        var _c;
        for (var i = 0; i < me.items.length; i++) {
            _c = me.items[i];

            if (_c && _c.removeAll) {
                _c.removeAll();
            }
            if (_c && _c.remove) {
                _c.remove();
            }
            delete Rsd.objects[_c.id];
        }

        while (me.items.length > 0) {
            me.items.splice(0, 1);
        }
        if (this.body.element) {
            this.body.element.innerHTML = null;
        }

    },

    /**
     * */
    onBeforeShow: function onBeforeShow() {
        this.events.fire(this, 'beforeshow', arguments);
    },
    /**
     * 
     * @param {*} style 
     */
    showMax: function showMax(style) {
        this.resizeObserver && this.resizeObserver.unobserve(this.dom);
        this._orgin_position = { top: this.dom.style.top || 'unset', right: this.dom.right || 'unset', bottom: this.style.bottom || 'unset', left: this.style.left || 'unset' };
        this.animate(Rsd.apply({ top: '0px', left: '0px', width: '100%', height: '100%', overflow: 'auto' }, style || {}), 500);
    },
    /**
     * 
     */
    showMini: function showMini(style) {
        var me = this;
        this.resizeObserver && this.resizeObserver.unobserve(this.dom);
        this._orgin_position = {
            top: this.dom.style.top || 'unset',
            right: this.dom.style.right || 'unset',
            bottom: this.style.bottom || 'unset',
            left: this.style.left || 'unset'
        };

        this.dom.style.overflow = 'hidden';
        var top = 'unset', left = 'unset', right = 'unset', bottom = 'unset';
        if (this._orgin_position.top != 'unset') {
            top = Number.parseInt(this.dom.parentNode.clientHeight) - 60 - (style.bottom != 'unset' ? Number.parseInt(style.bottom) : 0);
        }
        if (this._orgin_position.bottom != 'unset') {
            bottom = Number.parseInt(this.dom.parentNode.clientHeight) - 60 - (style.top != 'unset' ? Number.parseInt(style.top) : 0);
        }
        if (this._orgin_position.left != 'unset') {
            left = Number.parseInt(this.dom.parentNode.clientWidth) - 300 - (style.right != 'unset' ? Number.parseInt(style.right) : 0);
        }
        if (this._orgin_position.right != 'unset') {
            right = Number.parseInt(this.dom.parentNode.clientWidth) - 300 - (style.left != 'unset' ? Number.parseInt(style.left) : 0);
        }
        //console.log(this._orgin_position);
        //console.log(top,left,bottom,right);
        me.animate(Rsd.apply(style || {}, { top: top, left: left, right: right, bottom: bottom, width: '300px', height: '60px' }), 550, null, null, function () { });

    },
    /**
     * 
     * @param {*} style 
     */
    showNormal: function showNormal(style) {
        var me = this;
        var _style = Rsd.apply(style || {}, this._orgin_position);
        _style.width = this.width;
        _style.height = this.height;
        this.animate(_style, 200, null, null, function () { });

        this.dom.style.overflow = 'auto';
        //this._orgin_position=null;
        setTimeout(function () {
            me.resizeObserver && me.resizeObserver.observe(me.dom);
        }, 500);
    },
    /**
     * @description 以模态框的方式打开，参数格式：(parent), (positon), (parent,positon), (parent,positon,animate), (parent,positon,animate,speed) (parent,positon,animate,speed,callback) 
     * @description 指定x, y 值，可以页面展示效率
    *  @param parent 要展示的窗体 所在父窗体，多个dialog打开时，根据parent不同会设置多个蒙板
    *  @param position 位置：{top:0,left:0,right:null,bottom:null} 
    *  @param {string|Object}  animate 动画：fadeIn，slideDown,{top:30,left:100,backgroudColor:'red'}
    *  @param speed 打开速度
    *  @param callback 回调函数
    * */
    showDialog: function showDialog(parent, position, animate, speed, callback) {
 
        if (this.floating == false && this.fixed == false) {
            console.log(this);
            throw new Error("Property 'floating' or 'fixed' must value  is true.");
        }
        //不强制 dialog 使用 modular ，默认使用，在./app/单页面应用下，可以手动设置 不使用modular
        // if(this.modular.value == false)
        // {
        //     throw new Error("Property 'modular' is not true.");
        // }

        var me = this;
        //debugger;
        var _p = null, _position = null, _animate = null, _speed = null, _callback = null;

        if (arguments.length == 5) {
            _p = parent, _position = position, _animate = animate, _speed = speed, _callback = callback;
        }
        else {
            for (var i in arguments) {
                //console.log(arguments[i]);
                if (arguments[i] == null) {
                    continue;
                }
                if (Rsd.isString(arguments[i])) {
                    if (',left,right,center,position'.indexOf(arguments[i].toLowerCase()) > 0 && _position === null) {
                        _position = arguments[i];
                        continue;
                    }
                    if (',fadein,fadeout,'.indexOf(arguments[i].toLowerCase()) > 0 && _animate === null) {
                        _animate = arguments[i];
                        continue;
                    }
                    if (_callback === null) {
                        _callback = arguments[i];
                        continue;
                    }

                }

                if (arguments[i] instanceof Rsd.common.ComponentX || arguments[i] instanceof HTMLElement) {
                    _p = arguments[i];
                    continue;
                }
                if (Rsd.isObject(arguments[i]) && _position === null) {
                    _position = arguments[i];
                    continue;
                }

                if (Rsd.isObject(arguments[i]) && _animate === null) {
                    _animate = arguments[i];
                    continue;
                }

                if (Rsd.isFunction(arguments[i]) && _callback === null) {
                    _callback = arguments[i];
                    continue;
                }
                if (Rsd.isNumber(arguments[i]) && _speed === null) {
                    _speed = arguments[i];
                    continue;
                }
            }
        }
        //console.log(arguments);
        _p = _p || document.body;

        var _p_dom = _p;
        if (_p_dom instanceof Rsd.container.Component) {
            _p_dom = _p.dom;
        }

        var _top = null, _left = null, _right = null, _bottom = null;
        _position = _position || 'center';
        if (Rsd.isString(_position)) {
            switch (_position) {
                case "left":
                    _left = 0, _top = 0, _bottom = 0;
                    break;
                case "right":
                    _right = 0, _top = 0, _bottom = 0;
                    break;
                case "center":
                    if (!me.resizeObserver) {

                        //监听自身和父容器的尺寸变化
                        me.resizeObserver = new ResizeObserver(function (entries) {

                            for (let entry of entries) {

                                if (entry.contentRect.height == 0 || entry.contentRect.width == 0) {
                                    continue;
                                }
                                //父容器宽高
                                var _w = _p_dom.clientWidth > window.screen.availWidth ? window.screen.availWidth : _p_dom.clientWidth;
                                var _h = _p_dom.clientHeight > window.screen.availHeight ? window.screen.availHeight : _p_dom.clientHeight;
                                //
                                var width = me.dom.clientWidth;
                                var height = me.dom.clientHeight;

                                _left = (_w - width) / 2;
                                _top = ((_h - height) * 3) / 10;

                                //设置计算后的初始位置
                                if (_left != null && _top != null) {

                                    me.setPosition(_left < 0 ? 0 : _left, _top < 0 ? 0 : _top, null, null);
                                }
                                else {
                                    console.error('未能准确计算出位置信息:{x:' + _left + ',y:' + _top + '},dialog{width:' + me.width + 'height:' + me.height + '}');
                                }
                            }
                        });

                        me.resizeObserver.observe(me.dom);
                        me.resizeObserver.observe(_p_dom);

                        // // 取消监听特定元素
                        // me.resizeObserver.unobserve(element); 
                        // // 取消监听所有元素
                        // me.resizeObserver.disconnect();
                    }
                    break;
                case "default":
                default:
                    break;
            }

        }

        if (Rsd.isObject(_position)) {
            _top = _position.top == undefined ? null : _position.top;
            _left = _position.left == undefined ? null : _position.left;
            _right = _position.right == undefined ? null : _position.right;
            _bottom = _position._bottom == undefined ? null : _position._bottom;
        }

        //设置指定的初始位置
        if (_left != null || _top != null || _right != null || _bottom != null) {

            me.setPosition(_left, _top, _right, _bottom);
        }
        if (this.isRendered() == false) {

            this.renderTo(_p_dom);
        }
        var _z_index = 0;
        //以模式框 形式展示
        //console.log(this.modular);
        if (this.modular.value) {
            var _parent = _p_dom;
            var _id = "__modular_bg__" + ((_parent && _parent.id) || 'body');
            var _m_bg = document.getElementById(_id)

            if (Rsd.isEmpty(_m_bg)) {

                _m_bg = document.createElement("div");
                _m_bg.setAttribute("id", _id);
                _m_bg.style.background = "#000";
                _m_bg.style.width = "100%";
                _m_bg.style.height = "100%";
                _m_bg.style.position = "fixed";
                _m_bg.style.top = "0";
                _m_bg.style.left = "0";

                _m_bg.style.opacity = "0.3";
                _m_bg.style.filter = "Alpha(opacity=30)";

                _m_bg.opacity = Number(_m_bg.style.opacity);

                _m_bg.dialogs = [];
                if (this.modular.animate) {
                    var _o = Number(_m_bg.style.opacity);
                    var _i = 1;
                    var _j = 1;
                    var _k = setInterval(function () {

                        _m_bg.style.opacity = _o + 0.01 * _j;
                        _i++;
                        _i = _i % 200;
                        if (_i > 100) {
                            _j = 200 - _i;
                        } else {
                            _j = _i;
                        }
                        if (_i == 0) {
                            clearInterval(_k);
                        }

                    }, 10);

                }
                _m_bg.intervalKey = _k;
            }
            else {
                clearInterval(_m_bg.intervalKey);
                _m_bg.style.opacity = _m_bg.opacity; 
            }
            var _style = this.modular.style || {}; 
 
            this.setElStyle(_m_bg, _style);
 
            _m_bg.count = _m_bg.count || 0;
            _m_bg.count++;
            _z_index = Rsd.getZIndex(_m_bg.count * 2);//向上层 提升 背景框 ，（背景框 和 模式窗口 各占1层，所以 需要+1层）

            this.on('beforeshow', function () {
                //debugger 
                //console.log(this.$className);

                if (this.$className != "Rsd.control.WaitingBox"
                    && this.$className != 'Rsd.control.MessageBox') {
                    if (_m_bg.dialogs.length > 0) {
                        me.delayShow = 800;
                        _m_bg.dialogs[_m_bg.dialogs.length - 1].showMini({ top: 'unset', bottom: '0px', left: '120px' });
                    }
                    _m_bg.dialogs.push(this);
                }
                _m_bg.style.zIndex = _z_index;
                _parent.appendChild(_m_bg);
                _parent.setAttribute("overflow", _parent.style.overflowunset || 'unset');
                _parent.style.overflow = "hidden";

                if (_p instanceof Rsd.container.Component) {
                    _p.setElStyle('dom', { opacity: 0.95 }); 
                }
            });

            this.on('afterclose', function () {
                //debugger

                if (_m_bg) {

                    if (this.$className != "Rsd.control.WaitingBox"
                        && this.$className != 'Rsd.control.MessageBox') {

                        if (_m_bg.dialogs[_m_bg.dialogs.length - 1] == me) {
                            _m_bg.dialogs.pop();
                        }
                        if (_m_bg.dialogs.length > 0) {
                            var dialog = _m_bg.dialogs[_m_bg.dialogs.length - 1];
                            dialog.showNormal(); 
                        }

                    }

                    _m_bg.count--;//减1
                    if (_m_bg.count > 0) {

                        _m_bg.style.zIndex = Rsd.getZIndex(_m_bg.count * 2);//背景框 和 模式窗口 各占1 需要-1 
                        var dialog = _m_bg.dialogs[_m_bg.dialogs.length - 1]; 
                        if(dialog.modular && dialog.modular.style && dialog.modular.style.opacity)
                        {
                            _m_bg.style.opacity = dialog.modular.style.opacity;
                        }

                        return;
                    }
                    else {
                        _parent.style.overflow = _parent.getAttribute("overflow") || "unset";
                        try {

                            _parent.removeChild(_m_bg);

                        } catch (error) {

                        }
                    } 
                }
                if (_p instanceof Rsd.container.Component) {
                    _p.setElStyle('dom', { opacity: 1 });
                }
            });

        }

        this.dom.style.zIndex = _z_index + 1;

        //console.log(_m_bg.count ,'bg_'+ _m_bg.style.zIndex,'dom_'+ this.dom.style.zIndex,this.dom.id);
        //
        this.show(function () {
            //回调  
            Rsd.callFunction(this, _callback);
        });

        //延时展示
        setTimeout(function () {
            //启动动画效果
            if (_animate) {
                _animate.opacity = 1;
                me.animate(_animate, _speed || 80, function () { });
            }
            else {
                me.setElStyle('dom', { opacity: 1 });
            }
        }, me.delayShow || 500);

        //console.log(_position);
        if (_position == "center"
            && (_left === null || _top === null || me.width == "auto" || me.height == "auto")) {
            //console.log('进入窗体大小监控程序');
            //以实际高度 计算位置 
            var _timer = 10;//监控10次
            var _width = me.dom.clientWidth;
            var _height = me.dom.clientHeight;
            //位置参数 不全，监听控件自身尺寸变化 后调整位置
            //未指定显示位置 ，计算默认显示位置
            //显示后 set position  ，确保me.dom.clientWidth和me.dom.clientHeight值有效
            var __id = setInterval(function () {

                _timer--;
                if (_timer == 0) {
                    clearInterval(__id);
                }

                if (me.dom.clientWidth == _width
                    && me.dom.clientHeight == _height) {
                    return;
                }

                _width = me.dom.clientWidth;
                _height = me.dom.clientHeight;

                _w = _p_dom.clientWidth > window.screen.availWidth ? window.screen.availWidth : _p_dom.clientWidth;
                _h = _p_dom.clientHeight > window.screen.availHeight ? window.screen.availHeight : _p_dom.clientHeight;

                if (_left == null || me.width == "auto") {

                    _left = (_w - me.dom.clientWidth) / 2;
                }

                if (_top == null || me.height == "auto") {
                    _top = ((_h - me.dom.clientHeight) * 3) / 10;
                }

                if (_left < 0) {
                    _left = 0;
                }
                if (_top < 0) {
                    _top = 0;
                }
                //调试
                //console.log('in single dialog','obj:',me.width,me.height,'client:',_width,_height,'parent:',_w,_h,'position:',_left,_top,'parent is ',_p_dom.tagName);
                //再次调整位置
                //me.setPosition(_left, _top,null,null);
                //以动画的形式调整位置
                me.animate({ left: _left, top: _top }, 200);

            }, 100);

        }

        return this;
    },
    /**
     *  @public
     *  @description 将控件以动画的形式将对象显示出来
     *  @param {string|Object} animate 动画：fadeIn,slideDown,{top,30,left:100,backgroudColor:'red'}
     *  @param speed 速度
     *  @callback speed 速度
     * */
    show: function show(animate, speed, callback) {

        this.markTime('showStartTime');

        this.onBeforeShow();

        var me = this;

        if (this.isRendered() == false) {

            this.renderTo(this.parent || document.body);

            setTimeout(function () {
                //Opacity在Layout中会被设置为1
                me.doLayout();

            }, me.delayShow || 100);
        }

        this.dom.focus();

        this.callParentFn('show', arguments);

        this.onAfterShow();
        // 不处理回调 父类中已处理
        return this;
    },

    /**
    * */
    onAfterShow: function onAfterShow() {
        this.events.fire(this, 'aftershow', arguments);
    },

    /**
     *@description 关闭窗口 设置this.closeCancel=true 可以阻止窗口关闭
     * */
    close: function close(animate, speed, style, callback) {

        //拦截 close 方法 前置动作 因为事件可以是多个注册事件，所以在触发时 没法有返回值
        this.events.fire(this, 'beforeclose', arguments);
        if (this.closeCancel === true) {
            return;
        }
        var _animate = null;
        var _speed = 0;
        var _callback = null;
        var _style = null;
        var _delay = null;
        //参数处理
        for (var i = 0; i < arguments.length; i++) {

            if (arguments[i] == null || arguments[i] == undefined) {
                continue;
            }
            if (Rsd.isFunction(arguments[i])) {
                _callback = arguments[i];
                continue;
            }
            if (Rsd.isObject(arguments[i])) {
                _style = arguments[i];
                continue;
            }
            if (_animate == null && Rsd.isString(arguments[i])) {
                _animate = arguments[i];
                continue;
            }

            if (_speed == 0 && Rsd.isNumber(arguments[i])) {
                _speed = arguments[i];
                continue;
            }
            if (_speed > 0 && Rsd.isNumber(arguments[i])) {
                _delay = arguments[i];
                continue;
            }
        }

        var me = this;
        var _fn = function () {
            me.removeAll();
            me.remove();

            Rsd.callFunction(me, _callback);
        }

        var _param = _style || {};

        setTimeout(function () {

            if (Rsd.isEmpty(_param) && _animate) {
                if (Rsd.isEmpty(_param) && _animate) {

                    //_animate 动画参数映射 _param={};
                    switch (_animate.toLowerCase()) {
                        case 'fadeout':
                            _param = { opacity: 0 };
                            _speed = _speed || 150;

                            break;
                        default:
                            console.error(_animate + '动画参数映射，暂未开发。');
                            break;
                    }
                }
            }

            if (!Rsd.isEmpty(_param) || _speed > 0) {
                //params, speed,delay,fun, callback
                me.animate(_param, _speed, _delay || 0, 'ease-out', _fn);

            } else {
                _fn();
            }

        }, 0);
        //注销 拖动事件
        if (this.isDialog && this.draggable) {
            Rsd.offDragOver(null, this.id);
            Rsd.offDragLeave(null, this.id);
            Rsd.offDrop(null, this.id);
        }
        //拦截 close 方法 后置动作
        this.events.fire(this, 'afterclose', arguments);
    },

    /**
     * 
     * */
    getItemByXtype: function getItemByXtype(xtype) {

        function iterate(parent) {
            var _item = null;
            if (parent.items) {
                for (var i = 0; i < parent.items.length; i++) {
                    if (parent.items[i].xtype == xtype) {
                        _item = parent.items[i];
                        break;
                    }
                    _item = iterate(parent.items[i]);
                    if (_item != null) {
                        break;
                    }
                }
            }
            return _item;
        }

        return iterate(this);
    },
    /**
     * @description 根据id 或 name 获取Item 
     * @param {*} key 
     * @returns 
     */
    get: function get(key) {
        var item = this.getItemById(key);
        if (item) {
            return item;
        }
        return this.getItemByName(key);
    },
    /**
     * @description 根据ID获取,支持向下递归查找
     * */
    getItemById: function getItemById(id) {

        if (Rsd.isEmpty(id)) {
            return null;
        }
        function iterate(parent) {
            var _item = null;
            if (Rsd.isArray(parent.items)) {

                for (var i = 0; i < parent.items.length; i++) {

                    var _child = parent.items[i];
                    if (_child instanceof Rsd.common.ComponentX) { }
                    else {
                        if (_child.innerCtrl && _child.innerCtrl instanceof Rsd.common.ComponentX) {
                            _child = _child.innerCtrl;
                        }
                    }

                    //console.log(_child.xtype,'getItemById',_child.id);

                    if (_child.id && _child.id == id) {
                        _item = _child;
                        break;
                    }

                    _item = iterate(_child);

                    if (_item != null) {
                        break;
                    }
                }
            }
            return _item;
        }

        return iterate(this);
    },

    /**
    * 根据Name获取
    * */
    getItemByName: function getItemByName(name) {

        if (Rsd.isEmpty(name)) {
            return null;
        }
        function _fn(parent) {
            //debugger;
            var _item = null;
            if (Rsd.isArray(parent.items)) {


                for (var i = 0; i < parent.items.length; i++) {

                    if (parent.items[i].name && parent.items[i].name == name) {
                        _item = parent.items[i];
                        break;
                    }

                    _item = _fn(parent.items[i]);
                    if (_item != null) {
                        break;
                    }
                }
            }
            return _item;
        }

        return _fn(this);
    },

    /**
     * */
    setHeaderVisible: function setHeaderVisible(flag) {
        this.header.visible = flag;
        if (this.header.element) {
            this.header.element.style.display = (this.header.visible == false ? 'none' : 'inline-block');
        }
    },
    /**
     * 加载数据
     */
    loadData: function loadData(data,callback) {
        _data = data || this.dataSource || {};
        for (var i in this.items) {
            if (this.items[i].loadData) {
                this.items[i].funApplyByIOC(this.items[i].loadData, [_data[this.items[i].name]]);
            }
        }
        if(callback)
        {
            callback(_data);
        }    
    }


}, function (type) {
    {
        var _itemsGetter = function () {
            //debugger;

            var __name = '__items';

            //console.log(this.$className);
            //console.log(this.hasOwnProperty(__name));

            if (!this.hasOwnProperty(__name)) {

                this[__name] = [];

                var _tmp = this;

                while (_tmp.$className != 'Rsd.container.Component'
                    && !_tmp.__proto__.hasOwnProperty(__name)) {
                    _tmp = _tmp.__proto__;
                }
                if (_tmp.__proto__.hasOwnProperty(__name)) {
                    if (Rsd.isArray(_tmp.__proto__[__name])) {
                        for (var i in _tmp.__proto__[__name]) {
                            this[__name].push(Rsd.clone(_tmp.__proto__[__name][i]));
                        }
                    }
                    else {
                        Rsd.error(_tmp.__proto__.$className + ' items is not array.');
                    }
                }
            }

            return this[__name];
        };
        var _itemsSetter = function (items) {
            if (!Rsd.isArray(items)) {
                throw new Error('items is not array.');
            }
            for (var i = 0; i < items.length; i++) {
                if (!Rsd.isObject(items[i])) {
                    throw new Error('items[' + i + '] is not a object.');
                }
                this.items[i] = items[i];
            }

        }

        this.defineProperty(type, "items", _itemsGetter, _itemsSetter, true);

        var _headerGetter = function () {

            if (this.hasOwnProperty('__header') == false) {

                this.__header = Rsd.apply({
                    tagName: this.headerTagName,
                    cls: this.headerCls,
                    style: this.headerStyle,
                    content: '',
                    xtype: null,
                    position: 'top',
                    align: 'center',
                    space: 10,
                    cls: null,
                    visible: null,
                    element: null
                }, this.__proto__['__header'] || {});
            }

            if (this.__header.visible === undefined || this.__header.visible === null) {

                this.__header.visible = (Rsd.isString(this.__header.content) && this.__header.content.length > 0);
                this.__header.visible = this.__header.visible || (this.__header.content instanceof Rsd.common.ComponentX);
                this.__header.visible = this.__header.visible || (this.__header.xtype && this.__header.xtype.length > 0);
            }

            return this.__header;
        };
        var _headerSetter = function (header) {

            if (this.hasOwnProperty('__header') == false) {
                this.__header = Rsd.apply({
                    tagName: this.headerTagName,
                    cls: this.headerCls,
                    style: this.headerStyle,
                    content: '',
                    xtype: null,
                    position: 'top',
                    align: 'center',
                    space: 10,
                    cls: null,
                    visible: true,
                    element: null
                }, this.__proto__['__header'] || {});
            }
            if (Rsd.isObject(header)) {
                this.__header.visible = true;
                Rsd.apply(this.__header, header);
            }
            if (Rsd.isString(header)) {
                this.__header.visible = true;
                this.__header.content = header;
            }
            if (header === undefined || header === null || header === false) {
                this.__header.visible = false;
            }

        };

        this.defineProperty(type, "header", _headerGetter, _headerSetter, true);

        var _bodyGetter = function () {

            if (this.hasOwnProperty('__body') == false) {
                this.__body = {
                    element: null,
                    tagName: this.bodyTagName,
                    cls: this.bodyCls,
                    style: this.bodyStyle
                }
            }

            return this.__body;
        };
        var _bodySetter = function (value) {

            if (Rsd.isEmpty(value)) {
                return;
            }
            if (value instanceof Element) {
                this.body.element = value;
                return;
            }
            if (Rsd.isString(value)) {
                this.body.tagName = value;
                return;
            }
            this.__body = value;
        }

        this.defineProperty(type, "body", _bodyGetter, _bodySetter, false);

        var _titleGetter = function () {

            return this.header.content;
        };
        var _titleSetter = function (value) {

            if (Rsd.isEmpty(this.header.content) || Rsd.isString(this.header.content)) {
                this.header.content = value;
                return;
            }
            //this.header.element.appendChild(document.createTextNode(this.header.content));//不支持html标签
            if (this.headerTagName.toLowerCase() == 'img') {
                if (Rsd.empty(this.header.content)) {

                    this.header.element.src = Rsd.emptyImage();
                }
                else {
                    this.header.element.src = this.header.content;
                }
                return;
            }
            //console.log(this.header);
            if (this.header && this.header.content instanceof Rsd.common.ComponentX) {
                //console.log(this.header.content.title||'is empty')
                this.header.content.title = value;
                return;
            }

            if (this.header && this.header.content instanceof Element) {
                this.header.content.innerHTML = value;
                return;
            }

            if (this.header && this.header.element && !this.closeBtn) {
                this.header.element.innerHTML = value;
                return;
            }

            return;

        };
        this.defineProperty(type, "title", _titleGetter, _titleSetter, true);

        //组件数据源属性是 dataSource ,页面数据源是data
        var _dataGetter = function () {

            if (!this.hasOwnProperty('__data_source')) {
                this.__data_source = {};
            }
            return this.__data_source;
        };
        var _dataSetter = function (value) {

            this.__data_source = value;
            return;

        };
        this.defineProperty(type, "dataSource", _dataGetter, _dataSetter, true);

        var _modularGetter = function () {

            if (Rsd.isNullOrUndefined(this.__modular)) {
                this.__modular = { value: false, animate: false, style: null };
            }
            return this.__modular;
        };
        var _modularSetter = function (value) {

            if (Rsd.isBoolean(value)) {
                this.modular.value = value;
                return;
            }
            if (Rsd.isObject(value)) {
                Rsd.apply(this.modular, value);
                return;
            }

            console.error('set modular error value ', value);

            return;

        };
        this.defineProperty(type, "modular", _modularGetter, _modularSetter, true);

        var _layoutGetter = function () {

            if (Rsd.isNullOrUndefined(this.__layout)) {
                this.__layout = {
                    type: 'fit',
                    align: 'left',//start,center,end,stretch，扩展：top，right,left,bottom
                    wrap: null,//wrap or nowrap
                    content: null//主轴和交叉的对齐方式
                };
            }
            return this.__layout;
        };
        var _layoutSetter = function (value) {

            if (Rsd.isString(value)) {
                this.layout.type = value;
                return;
            }

            if (Rsd.isObject(value)) {
                Rsd.apply(this.layout, value);
                return;
            }
            console.error('set layout error value ', value);
            return;

        };

        this.defineProperty(type, "layout", _layoutGetter, _layoutSetter, true);

    }
});
